#! /usr/bin/env python2  
# encoding=utf-8
import sys
reload(sys) 
sys.setdefaultencoding('utf8')
import os
ScriptPath = os.path.split( os.path.realpath( sys.argv[0] ) )[0]
import xmlrpclib
import ConfigParser
import datetime

# 超期未检电梯生成扣分事件，每月重复不计算

config = ConfigParser.RawConfigParser()
config.read(ScriptPath+'/sys.cfg')
url = config.get('odoo','host')
uid = 1
pwd = config.get('odoo','password')
db = config.get('odoo','db')
models = xmlrpclib.ServerProxy('{}/xmlrpc/2/object'.format(url))



def main():
    print u"开始更新电梯超期未检事件"
    # 超期未检验事件code
    over_code = config.get('risk-event','over_check_no')
    # 超期未检事件的ID
    over_code_id = models.execute_kw(db,uid,pwd,'tyibs.risk.event.category','search_read',[[['code','=',over_code]]],{'fields':['code']})[0]['id']
    # 所有超期未检电梯
    lifts = models.execute_kw(db,uid,pwd,'tyibs.base.lift','search_read',[[['next_check_date','<',datetime.datetime.now().strftime('%Y-%m-%d')]]],{'fields':['code']})
    lift_ids = [i['id'] for i in lifts]
    # PS:这里只需要大于本月1号就行，不存在下月分的事件
    over_check_lift_ids = [i['lift_id'] and i['lift_id'][0] or 0 for i in models.execute_kw(db,uid,pwd,'tyibs.risk.event.line','search_read',[[['event_code','=',over_code],['date','>',datetime.datetime.now().strftime('%Y-%m-01')]]],{'fields':['lift_id']})]
    # 相减得出需要生成的电梯ID
    push_lift_ids = [i for i in lift_ids if i not in over_check_lift_ids]
    if len(push_lift_ids)>0:
        print u"需要生成电梯超期未检事件"
    else:
        print u"无电梯超期未检事件"
    for p_lift in push_lift_ids:
        print p_lift
        models.execute_kw(db,uid,pwd,'tyibs.risk.event.line','create',[{
            'date':datetime.datetime.now().strftime('%Y-%m-%d'),
            'event_category_id':over_code_id,
            'lift_id':p_lift
        }])

if __name__ == '__main__':
    main()